<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Http\Forms\CrowdGoodForm;
use App\Modules\Crowd\Models\Crowd;
use App\Modules\Crowd\Models\CrowdGood;
use App\Modules\Order\Models\SupportOrder;
use App\Modules\Shop\Manager;
use App\Modules\Shop\Shop;
use App\Modules\User\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CrowdController extends ApiController
{
    public function index(Request $request)
    {
        $name = $request->input('name');
        $goods = $request->input('goods');

        $query = Crowd::query()
            ->join('users', 'users.id', '=', 'crowds.user_id')
            ->select('crowds.*', 'users.nickname', 'users.avatar')
            ->orderBy('crowds.created_at', 'desc');

        if (!empty($name)) {
            $query->where('nickname', 'like', '%'.$name."%");
        }
        if (!empty($goods)) {
            $query->where('title', 'like', '%'.$goods."%");
        }
        $data = $query->paginate(30);
        $support = SupportOrder::query()
            ->whereIn('crowd_id', $data->pluck('id')->all())
            ->where('status', SupportOrder::STATUS_SUCCESS)
            ->selectRaw('count(user_id) as count, crowd_id')
            ->groupBy('crowd_id')
            ->get()
            ->pluck('count', 'crowd_id');
        $sidebar = 'crowd';
        return view('crowd.index', compact('data', 'name', 'goods', 'support', 'sidebar'));
    }

    public function refund($id)
    {
        /** @var Crowd $crowd */
        $crowd = Crowd::query()
            ->where('id', $id)
            ->where('status', '!=', Crowd::STATUS_REFUND)
            ->first();
        if (is_null($crowd)) {
            return redirect()->back()->withErrors('众筹id错误');
        }
        $crowd->refund();
        return redirect()->back();
    }

    public function supportList($id)
    {
        $data = SupportOrder::query()
            ->where('crowd_id', $id)
            ->whereIn('status', [SupportOrder::STATUS_SUCCESS, SupportOrder::STATUS_REFUND])
            ->paginate();
        $user = User::query()->whereIn('id', $data->pluck('user_id')->all())->get()->keyBy('id');
        $sidebar = 'crowd';
        return view('crowd.support', compact('data', 'user', 'sidebar'));
    }

    public function supportRefund($id)
    {
        /** @var SupportOrder $support */
        $support = SupportOrder::query()
            ->where('id', $id)
            ->where('status', SupportOrder::STATUS_SUCCESS)
            ->first();
        if (is_null($support)) {
            return redirect()->back()->withErrors("数据错误");
        }
        if (!$support->refund()) {
            return redirect()->back()->withErrors('退款失败');
        }
        $crowd = Crowd::query()
            ->find($support->crowd_id);
        if ($crowd->user_id == $support->user_id) {
            $crowd->decrement('self_pay', $support->price);
        } else {
            $crowd->decrement('support_money', $support->price);
        }
        return redirect()->back();
    }

    public function getGoodList()
    {
        $shop = Manager::getShop();
        $data = CrowdGood::query()->paginate(20);
        $sidebar = 'good';
        return view('crowd.good', compact('data', 'shop', 'sidebar'));
    }

    public function createGood()
    {
        $shop = Shop::query()->where('status', Shop::STATUS_OPEN)->get()->pluck('name', 'id')->all();
        $form = $this->form(CrowdGoodForm::class, [
            'method' => 'PUT',
            'url' => route('admin.crowd.good.store'),
        ], [
            'shop' => $shop,
        ]);
        $sidebar = 'good';
        return view('crowd.form', compact('form', 'sidebar'));
    }

    public function storeGood()
    {
        $form = $this->form(CrowdGoodForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $data['price'] = $data['price'] * 100;
        $data['display_price'] = $data['display_price'] * 100;
        $data['status'] = CrowdGood::STATUS_OFF;
        CrowdGood::query()->create($data);
        return redirect()->route('admin.crowd.good');
    }

    public function editGood($id)
    {
        $good = CrowdGood::query()->find($id);
        $good->display_price /= 100;
        $good->price /= 100;
        $form = $this->form(CrowdGoodForm::class, [
            'method' => 'POST',
            'url' => route('admin.crowd.good.update', ['id' => $id]),
            'model' => $good,
        ]);
        $sidebar = 'good';
        return view('crowd.form', compact('form', 'sidebar'));
    }

    public function updateGood($id)
    {
        $form = $this->form(CrowdGoodForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $data['price'] = $data['price'] * 100;
        $data['display_price'] = $data['display_price'] * 100;
        $data['status'] = CrowdGood::STATUS_ON;
        CrowdGood::query()->where('id', $id)->update($data);
        return redirect()->route('admin.crowd.good');
    }

    public function status($id)
    {
        $goods = CrowdGood::query()
            ->where('id', $id)
            ->first();
        if ($goods->status == CrowdGood::STATUS_OFF) {
            $goods->update([
                'status' => CrowdGood::STATUS_ON,
            ]);
        } else {
            $goods->update([
                'status' => CrowdGood::STATUS_OFF,
            ]);
        }
        return redirect()->back();
    }
}
